package cool.taomu.toolkit.provider

import javax.inject.Provider
import com.google.common.util.concurrent.MoreExecutors
import java.util.concurrent.Executors
import com.google.common.util.concurrent.ListeningExecutorService
import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.google.inject.Inject
import javax.inject.Named
import org.slf4j.LoggerFactory

class ListeningExecutorServiceProvider implements Provider<ListeningExecutorService> {

	val LOG = LoggerFactory.getLogger(ListeningExecutorServiceProvider);
	
	@Inject(optional=true)
	@Named("taomu.thread.pool.size")
	Integer poolSize;

	override get() {
		
		if (poolSize === null) {
			val coreNumber = Runtime.getRuntime().availableProcessors;
			poolSize = coreNumber * 2
		}
		LOG.info("创建线程池大小：{}",poolSize);
		val l = MoreExecutors.listeningDecorator(
			Executors.newFixedThreadPool(poolSize,
				new ThreadFactoryBuilder().setNameFormat("taomu-pool-%d").setDaemon(true).build()))
		Runtime.runtime.addShutdownHook(new Thread() {
			override run() {
				l.shutdown();
			}
		})
		return l;
	}

}
